GNU ?= riscv64-linux-gnu

COPS += -save-temps=obj -g -O0 -Wall -nostdlib -Iinclude -mcmodel=medany -mabi=lp64 -march=rv64imafd -fno-PIE -fomit-frame-pointer

##############
#  build rt-rvos
##############
BUILD_ROOT= output
BUILD_DIR = $(BUILD_ROOT)/os
SRC_DIR = src

BSP_DIR = bsp
SRC_QEMU_BOARD = bsp/qemu-virt64-riscv/drivers/uart
BUILD_QEMU_BOARD = $(BUILD_ROOT)/bsp/qemu-virt64-riscv/drivers/uart

all : clean rt-rvos.bin

# Check if verbosity is ON for build process
CMD_PREFIX_DEFAULT := @
ifeq ($(V), 1)
	CMD_PREFIX :=
else
	CMD_PREFIX := $(CMD_PREFIX_DEFAULT)
endif

clean :
	rm -rf $(BUILD_ROOT)  *.bin  *.map *.elf


$(BUILD_DIR)/%_c.o: $(SRC_DIR)/%.c
	$(CMD_PREFIX)mkdir -p $(BUILD_DIR); echo " CC   $@" ; $(GNU)-gcc $(COPS) -c $< -o $@

$(BUILD_DIR)/%_s.o: $(SRC_DIR)/%.S
	$(CMD_PREFIX)mkdir -p $(BUILD_DIR); echo " AS   $@"; $(GNU)-gcc $(COPS) -c $< -o $@

$(BUILD_QEMU_BOARD)/%_c.o: $(SRC_QEMU_BOARD)/%.c
	$(CMD_PREFIX)mkdir -p $(BUILD_QEMU_BOARD); echo " CC   $@" ; $(GNU)-gcc $(COPS) -c $< -o $@


C_FILES = $(wildcard $(SRC_DIR)/*.c)
ASM_FILES = $(wildcard $(SRC_DIR)/*.S)
OBJ_FILES = $(C_FILES:$(SRC_DIR)/%.c=$(BUILD_DIR)/%_c.o)
OBJ_FILES += $(ASM_FILES:$(SRC_DIR)/%.S=$(BUILD_DIR)/%_s.o)


QEMU_BOARD_C_FILES = $(wildcard $(SRC_QEMU_BOARD)/*.c)
QEMU_BOARD_OBJ_FILES = $(QEMU_BOARD_C_FILES:$(SRC_QEMU_BOARD)/%.c=$(BUILD_QEMU_BOARD)/%_c.o)



DEP_FILES = $(OBJ_FILES:%.o=%.d)
-include $(DEP_FILES)

rt-rvos.bin: $(SRC_DIR)/linker.ld $(OBJ_FILES) $(QEMU_BOARD_OBJ_FILES)
	$(CMD_PREFIX)$(GNU)-ld -T $(SRC_DIR)/linker.ld -o $(BUILD_DIR)/rt-rvos.elf  $(OBJ_FILES) $(QEMU_BOARD_OBJ_FILES) -Map rt-rvos.map; echo " LD $(BUILD_DIR)/rt-rvos.elf"
	$(CMD_PREFIX)$(GNU)-objcopy $(BUILD_DIR)/rt-rvos.elf -O binary rt-rvos.bin; echo " OBJCOPY rt-rvos.bin"
	$(CMD_PREFIX)cp $(BUILD_DIR)/rt-rvos.elf rt-rvos.elf


##############
#  run qemu
##############
QEMU_FLAGS  += -nographic -machine virt -m 128M -smp 1
QEMU_BIOS = -bios none
QEMU=qemu-system-riscv64-7.0
run:
	$(QEMU) $(QEMU_FLAGS) $(QEMU_BIOS) -kernel rt-rvos.elf
debug:
	$(QEMU) $(QEMU_FLAGS) $(QEMU_BIOS) -kernel rt-rvos.elf -S -s
